package com.xiaoyu.im.provider;

import com.xiaoyu.base.DBCall;
import com.xiaoyu.base.entity.MessageEntity;
import com.xiaoyu.base.utils.ListUtil;
import com.xiaoyu.im.datamodel.AppMessage;

import java.util.List;

public class MessageListPaginator {

    private static final int DEFAULT_NUM_PER_PAGE = 20;

    private final AbstractMessageDataProvider mMessageProvider;
    private long mLastTime;
    private String mLastId;

    public MessageListPaginator(AbstractMessageDataProvider messageProvider) {
        this.mMessageProvider = messageProvider;
    }

    public synchronized AbstractMessageDataProvider.SearchMessageResultWrapper loadMessageListWithWrapper(String chatId, String messageId) {
        reset();

        MessageEntity messageEntity = DBCall.call(database -> database.messageDao().getMessage(messageId));
        if (messageEntity != null) {
            AbstractMessageDataProvider.SearchMessageResultWrapper wrapper = mMessageProvider.loadMessagesWithWrapper(chatId, messageEntity.getDisplayTime(), messageId);
            updateLastMessage(wrapper.messages);
            return wrapper;
        }
        return null;
    }

    public synchronized List<AppMessage> loadMessageList(String chatId, boolean first) {
        if (first) {
            reset();
        }

        final List<AppMessage> list = mLastId == null ?
                mMessageProvider.loadMessages(chatId, DEFAULT_NUM_PER_PAGE) :
                mMessageProvider.loadMessages(chatId, mLastTime, mLastId, DEFAULT_NUM_PER_PAGE);
        updateLastMessage(list);
        return list;
    }

    private void updateLastMessage(List<AppMessage> list) {
        AppMessage lastMessage = ListUtil.getLast(list);
        if (lastMessage != null) {
            mLastTime = lastMessage.getDisplayTime();
            mLastId = lastMessage.id;
        }
    }

    public void reset() {
        mLastId = null;
        mLastTime = 0;
    }
}
